﻿Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Security.Cryptography
Imports System.Text
Imports log4net
Imports log4net.Config

Partial Class FctHierarchy
    Inherits System.Web.UI.Page

    Public sripttext As String
    Dim logger As log4net.ILog = LogManager.GetLogger("FctHierarchy")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        'Session("PlanYear") = "2557"
        If Page.IsPostBack = False Then
            PlanYearsTxt.Text = Session("PlanYear")
            Session("PlanYearsTxt") = PlanYearsTxt.Text
            Session("GroupTextBox") = GroupTextBox.Text
        End If
      
        Label1.Text = "ระบบจัดทำงบประมาณ >> ตั้งค่าระบบ >> Fund Center Hierarchies"
    End Sub

    Protected Sub WebCombo1_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs)
        Dim adap As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim dt As New FundCenter2.FundCenterHierarchiesDataTable

        dt = adap.GetDataByYear(Val(PlanYearsTxt.Text), Session("GroupTextBox"))

        Dim dView As New DataView(dt)
        dView.Sort = "Fundcenter_FundCenterCode ASC"
        e.DataSource = dView
    End Sub

    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        Dim FCTDataSet As New DataSet
        GetData(WebCombo1.Value, Val(Session("PlanYearsTxt")), Session("GroupTextBox"), FCTDataSet)

        e.DataSource = FCTDataSet.Tables("Items")
    End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim FctCode As String = WebGrid1.SelectedRowKeyValue
            Dim PlanYear As Integer = Session("PlanYearsTxt")
            Dim FctGroup As String = Session("GroupTextBox")

            DeleteSub(FctCode, FctGroup, PlanYear)

            WebGrid1.ClientAction.Refresh()
        End If
    End Sub
    
    Sub DeleteSub(FctCode As String, FctGroup As String, planYear As Integer)
        Dim adapter As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenterParent.FundCenterHierarchiesDataTable
        datatable = adapter.GetDataByParent(FctCode, FctGroup, planYear)
        For Each row As FundCenterParent.FundCenterHierarchiesRow In datatable
            DeleteSub(row.FundCenter_FundCenterCode, FctGroup, planYear)
        Next

        adapter.DeleteQuery(FctCode, FctGroup, planYear)

        logger.Info("User " & Session("users") & " delete fund center code " & FctCode & " of group " & FctGroup & " in year " & planYear)
    End Sub

    Sub Plot_Grid()
        Dim FCTDataSet As New DataSet
        GetData(WebCombo1.Value, PlanYearsTxt.Text, GroupTextBox.Text, FCTDataSet)
        WebGrid1.DataSource = FCTDataSet.Tables("Items")
        WebGrid1.DataBind()

    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        Session("PlanYearsTxt") = PlanYearsTxt.Text
        Session("GroupTextBox") = GroupTextBox.Text
        Plot_Grid()
        WebCombo1.ClearCachedDataSource()
        WebCombo1.DataBind()
    End Sub

    Sub GetData(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet)
        Dim dt As DataTable = ds.Tables.Add("Items")
        dt.Columns.Add("id", Type.GetType("System.Decimal"))
        dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
        dt.Columns.Add("Description", Type.GetType("System.String"))
        dt.Columns.Add("ParentCode", Type.GetType("System.String"))
        Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable

        Dim fadapter As New FundCenter2TableAdapters.FundCentersTableAdapter
        Dim r As DataRow
        r = dt.NewRow()
        r("FundCenterCode") = FundCenterCode
        r("Description") = FundCenterCode & "  " & fadapter.GetName(FundCenterCode, PlanYear)
        r("ParentCode") = ""
        dt.Rows.Add(r)

        datatable = adapter.GetDataByParent(FundCenterCode, PlanYear, FctGroup)
        For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
            GetChild(row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup)
        Next
    End Sub

    Sub GetChild(ByVal parent_id As String, ByRef ds As DataSet, ByRef dt As DataTable, PlanYear As Decimal, FctGroup As String)
        Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable

        datatable = adapter.GetDataByFctCode(parent_id, PlanYear, FctGroup)
        Dim r As DataRow
        Dim version As Integer = 1
        r = dt.NewRow()
        r("FundCenterCode") = parent_id
        For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
            r("Description") = parent_id & "  " & row.Description
            r("ParentCode") = row.ParentFundCenterCode

        Next
        dt.Rows.Add(r)
        datatable = adapter.GetDataByParent(parent_id, PlanYear, FctGroup)
        For Each row As FundCenter2.FundCenterHierarchiesRow In datatable

            GetChild(row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup)
        Next
    End Sub
   
    Protected Sub RegenBtn_Click(sender As Object, e As ImageClickEventArgs) Handles RegenBtn.Click
        Try
            Dim adap As New FundCenter2TableAdapters.FctHTableAdapter
            adap.DeleteYear(Val(PlanYearsTxt.Text))
            adap.RegenYear(Val(PlanYearsTxt.Text))

            Dim adapter As New FundCenterParentTableAdapters.FctParentTableAdapter
            Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
            Dim Hdatatable As New FundCenterParent.FctHDataTable
            adapter.DeleteByYear(Val(PlanYearsTxt.Text))
            Hdatatable = Hadapter.GetData(Val(PlanYearsTxt.Text))
            Dim FctCode As String
            Dim Grouppath As String = ""
            For Each row As FundCenterParent.FctHRow In Hdatatable
                FctCode = row.FundCenter_FundCenterCode
                adapter.InsertQuery(FctCode, Val(PlanYearsTxt.Text))
                If FctCode = "0000" Then
                    Grouppath = row.grouppath
                End If
            Next
            ' Exit Sub
            SetParent(Grouppath)

        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)

            sripttext = "<script>alert('ไม่สามารถปรับรายการได้กรุณาติดต่อผู้ดูแลระบบ')</script>"
            Exit Sub
        End Try

        Dim initLDAPPath As String = ""
        Dim initLDAPServer As String = ""
        Dim initShortDomainName As String = ""
        Dim usname As String = ""
        Dim pwd As String = ""
        Try
            initLDAPPath = ConfigurationManager.AppSettings("initLDAPPath")
            initLDAPServer = ConfigurationManager.AppSettings("initLDAPServer")
            initShortDomainName = ConfigurationManager.AppSettings("initShortDomainName")
            usname = ConfigurationManager.AppSettings("initLDAPusname")
            pwd = ConfigurationManager.AppSettings("initLDAPpwd")
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        Dim DomainAndUsername As String = ""
        Dim strCommu As String
        strCommu = "LDAP://" & initLDAPServer & "/" & initLDAPPath

        logger.Info("User " & Session("users") & " connect LDAP with path " & strCommu)

        Dim usadp As New CostCenterTableAdapters.UsersTableAdapter
        Dim usdt As New CostCenter.UsersDataTable
        usdt = usadp.GetData
        For Each item As CostCenter.UsersRow In usdt
            FctrGenClass.GenFctrView(item.UserName, Val(PlanYearsTxt.Text))

            Try

                Dim f_adapter As New LoginDSTableAdapters.LoginLockTableAdapter
                Dim f_datatable As New LoginDS.LoginLockDataTable

                ''gen from Code center
                'Dim entry As New DirectoryEntry(strCommu, usname, pwd)
                'Dim obj As Object

                'obj = entry.NativeObject
                'Dim search As New DirectorySearcher(entry)
                'Dim result As SearchResult
                'search.Filter = "(SAMAccountName=" + item.UserName.Trim + ")"
                'logger.Info("User " & Session("users") & " > SAMAccountName is " & item.UserName.Trim)
                'search.PropertiesToLoad.AddRange(New String() {"cn", "postalcode", "employeeid"})
                'result = search.FindOne()

                'Dim costcentercode As String = ""
                'If result Is Nothing Then
                '    logger.Info("User " & Session("users") & " > no result return from AD for user " & item.UserName.Trim)
                'Else
                '    logger.Info("User " & Session("users") & " > result return from AD")
                '    For Each prop As DictionaryEntry In result.Properties
                '        For Each inval As Object In prop.Value
                '            If prop.Key.ToString = "postalcode" Then
                '                costcentercode = inval.ToString.Trim
                '            End If
                '        Next
                '    Next
                'End If

                Dim costcentercode As String = item.FundCenter_FundCenterCode

                logger.Info("User " & Session("users") & " > cost center of user " & item.UserName & " is " & costcentercode)

                If costcentercode.Trim <> "" Then
                    GenCodeCenter(item.UserName, costcentercode, Val(PlanYearsTxt.Text))
                End If
            Catch ex As Exception
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try
        Next

        logger.Info("User " & Session("users") & " > generate fund center successfully.")

        sripttext = "<script>alert('ปรับปรุงรายการเรียบร้อย')</script>"
    End Sub

    Protected Sub WebGrid1_InitializeRow(sender As Object, e As RowEventArgs) Handles WebGrid1.InitializeRow
        e.Row.ExpandSelfRefRow()
    End Sub

    Sub SetParent(GroupPath As String)
        Dim adapter As New FundCenterParentTableAdapters.FctParentTableAdapter
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Dim level As Integer
        level = Len(GroupPath) / 2
        Hdatatable = Hadapter.GetDataByGPath(GroupPath, Val(PlanYearsTxt.Text))

        Dim FctCode As String
        Dim description As String
        For Each row As FundCenterParent.FctHRow In Hdatatable
            FctCode = row.FundCenter_FundCenterCode
            description = row.Description

        Next
        Hdatatable = Hadapter.GetDataByLikeGPath(GroupPath & "%", Val(PlanYearsTxt.Text))
        For Each row As FundCenterParent.FctHRow In Hdatatable
            If level = 1 Then
                adapter.UpdateParent1(FctCode, description, row.FundCenter_FundCenterCode)
            ElseIf level = 2 Then
                adapter.UpdateParent2(FctCode, description, row.FundCenter_FundCenterCode)
            ElseIf level = 3 Then
                adapter.UpdateParent3(FctCode, description, row.FundCenter_FundCenterCode)
            ElseIf level = 4 Then
                adapter.UpdateParent4(FctCode, description, row.FundCenter_FundCenterCode)
            ElseIf level = 5 Then
                adapter.UpdateParent5(FctCode, description, row.FundCenter_FundCenterCode)
            End If
            If row.grouppath <> GroupPath Then
                SetParent(row.grouppath)
            End If
        Next
    End Sub

    Sub GenCodeCenter(ByVal users As String, ByVal costcenter As String, ByVal planyear As Integer)
        Dim user_name As String = ""
        user_name = users

        Dim ccadap As New CostCenterTableAdapters.CostCentersTableAdapter
        Dim ccdt As New CostCenter.CostCentersDataTable
        ccdt = ccadap.GetDataByCCode(costcenter, planyear)

        'Dim usfadp As New CostCenterTableAdapters.UserFundCentersTableAdapter
        Dim fcadap As New fctrDSTableAdapters.fctr_viewTableAdapter

        Dim childadap As New LoginDSTableAdapters.Fcth2TableAdapter
        Dim childdt As New LoginDS.Fcth2DataTable
        Dim check As Integer = 0
        For Each item As CostCenter.CostCentersRow In ccdt
            'check = usfadp.CheckExist(planyear, user_name, item.FundCenter_FundCenterCode, item.FundCenter_FundCenterCode)
            'If check = 0 Then
            'usfadp.InsertUSF(planyear, Date.Now, user_name, user_name, item.FundCenter_FundCenterCode, item.FundCenter_PlanYear, item.FundCenter_FundCenterCode, item.FundCenter_PlanYear)
            'End If

            Dim chk0 As Integer
            chk0 = fcadap.CheckExist(item.FundCenter_FundCenterCode, user_name, planyear)
            logger.Info("checking user is exist => fund center = " & item.FundCenter_FundCenterCode & " user name = " & user_name & " plan year = " & planyear)
            If chk0 = 0 Then
                fcadap.Insert(Nothing, item.FundCenter_FundCenterCode, user_name, item.FundCenter_FundCenterCode, planyear)
                logger.Info("insert fctr_view with data " & "fund center = " & item.FundCenter_FundCenterCode & " username = " & user_name & " fund center = " & item.FundCenter_FundCenterCode & " plan year = " & planyear)
            End If
            childdt = childadap.GetData(item.FundCenter_FundCenterCode, planyear)
            For Each item2 As LoginDS.Fcth2Row In childdt
                Dim chk As Integer
                chk = fcadap.CheckExist(item2.FundCenter_FundCenterCode, user_name, planyear)
                If chk = 0 Then
                    fcadap.Insert(Nothing, item2.FundCenter_FundCenterCode, user_name, item2.parentcode, planyear)
                    logger.Info("insert fctr_view with data " & "fund center = " & item.FundCenter_FundCenterCode & " username = " & user_name & " parent fund center = " & item2.FundCenter_FundCenterCode & " plan year = " & planyear)
                End If
            Next
        Next
    End Sub

    Protected Sub PlanYearsTxt_TextChanged(sender As Object, e As EventArgs) Handles PlanYearsTxt.TextChanged
        Dim adap As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim dt As New FundCenter2.FundCenterHierarchiesDataTable

        dt = adap.GetDataByYear(Val(PlanYearsTxt.Text), Session("GroupTextBox"))

        Dim dView As New DataView(dt)
        dView.Sort = "Fundcenter_FundCenterCode ASC"
        WebCombo1.DataSource = dView

    End Sub
End Class
